package com.hq.shop15car.controller;

import com.hq.commons.common.R;
import com.hq.commons.constatns.AuthConstatns;
import com.hq.commons.constatns.CarConstatns;
import com.hq.commons.ov.Customer;
import com.hq.commons.ov.Goods;
import com.hq.shop15car.feign.api.GoodsService;
import com.hq.shop15car.ov.Car;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("carController")
public class CarController {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private GoodsService goodsService;

    @PostMapping("addCar")
    @ResponseBody
    public R addCar(Car car, HttpSession session, HttpServletResponse response,
                    @CookieValue(name = CarConstatns.ANNE_CAR_COOK_NAME, defaultValue = "")
                            String anneId) {
        Customer customer = (Customer) session.getAttribute(AuthConstatns.AUTH_SESSION);
        BoundHashOperations<String, Object, Object> hashOps = null;
        if (customer != null) {
//            已经登录
            Integer id = customer.getId();
            hashOps = redisTemplate.boundHashOps(CarConstatns.USERCARPRE + id);
//            hashOps.expire(100, TimeUnit.SECONDS);
//            hashOps.put(car.getGid().toString(), car.getSum().toString());
        } else {
//            没有登录
            if (StringUtils.isEmpty(anneId)) {
                anneId = UUID.randomUUID().toString();
                Cookie cookie = new Cookie(CarConstatns.ANNE_CAR_COOK_NAME, anneId);
                cookie.setMaxAge(60 * 60 * 24 * 7);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
            hashOps = redisTemplate.boundHashOps(CarConstatns.USERCARPRE);
        }
        hashOps.put(car.getGid().toString(), car.getSum().toString());
        return R.success();
    }

    @PostMapping("updateCar")
    @ResponseBody
    public R updateCar(Integer sum, String gid, String type, HttpSession session, ModelMap modelMap
            , @CookieValue(name = CarConstatns.ANNE_CAR_COOK_NAME, defaultValue = "") String anneId) {
        Customer customer = (Customer) session.getAttribute(AuthConstatns.AUTH_SESSION);
        BoundHashOperations<String, Object, Object> carMap = null;
        if (customer != null) {
            carMap = redisTemplate.boundHashOps(CarConstatns.USERCARPRE + customer.getId());

        } else {
            if (!StringUtils.isEmpty(anneId)) {
                carMap = redisTemplate.boundHashOps(CarConstatns.ANNE_CAR_COOK_NAME + anneId);
            }
        }
        if (sum > 1) {
            switch (type) {
                case CarConstatns.CAR_INCR:

                    carMap.increment(gid, 1);
                    break;
                case CarConstatns.CAR_DECR:
                    carMap.increment(gid, -1);
            }
        }
        return R.success();
    }

    @GetMapping("deleteCar")
    @ResponseBody
    public R deleteCar() {
        return R.success();
    }

    /**
     * @author: HQ
     * @return:
     * @time: 2021/7/22 16:58
     * @description: 展示购物车
     */
    @GetMapping("getCar")
    public String getCar(HttpSession session, ModelMap modelMap
            , @CookieValue(name = CarConstatns.ANNE_CAR_COOK_NAME, defaultValue = "") String anneId) {
        Customer customer = (Customer) session.getAttribute(AuthConstatns.AUTH_SESSION);
        BoundHashOperations<String, Object, Object> carMap = null;
        BigDecimal totalPrice = new BigDecimal(0.0);
        if (customer != null) {
            carMap = redisTemplate.boundHashOps(CarConstatns.USERCARPRE + customer.getId());

        } else {
            if (!StringUtils.isEmpty(anneId)) {
                carMap = redisTemplate.boundHashOps(CarConstatns.ANNE_CAR_COOK_NAME + anneId);
            }
        }
        List<Car> carList = new ArrayList<>();
        Map<Object, Object> entries = carMap.entries();
        for (Map.Entry<Object, Object> entry : entries.entrySet()) {
            Object key = entry.getKey();
            Object value = entry.getValue();
            Car car = new Car();
            int gid = Integer.parseInt(key.toString());
            car.setGid(gid);
            int sum = Integer.parseInt(value.toString());
            car.setSum(sum);
            Goods goods = goodsService.info(gid);
            car.setGoods(goods);
//            商品小计
            BigDecimal sumTotal = goods.getGprice().multiply(BigDecimal.valueOf(sum));
            car.setSumTotal(sumTotal);
            carList.add(car);
            totalPrice=totalPrice.add(sumTotal);
        }
        modelMap.put("carList", carList);
        modelMap.put("totalPrice", totalPrice);
        return "carList";
    }

    /**
     * @author: HQ
     * @return:
     * @time: 2021/7/22 16:57
     * @description: 合并购物车
     */
    @GetMapping("/mergeCar/{uid}/{anneId}")
    @ResponseBody
    public R mergeCar(@PathVariable Integer uid, @PathVariable String anneId) {
//        绑定用户id购物车
        BoundHashOperations<String, Object, Object> userIdHashOps = redisTemplate.boundHashOps(CarConstatns.USERCARPRE + uid);
        BoundHashOperations<String, Object, Object> anneIdHashOps = redisTemplate.boundHashOps(CarConstatns.USERCARPRE + anneId);

        Map<Object, Object> entries = anneIdHashOps.entries();
        Set<Map.Entry<Object, Object>> entrySet = entries.entrySet();
        for (Map.Entry<Object, Object> objectObjectEntry : entrySet) {
            Object key = objectObjectEntry.getKey();
            Object value = objectObjectEntry.getValue();
//            判断登录的购物车中是否有这个商品
            if (userIdHashOps.hasKey(key)) {
                Integer uint = Integer.parseInt(userIdHashOps.get(key).toString());
                Integer anInt = Integer.parseInt(value.toString());
                value = (uint + anInt) + "";
            } else {
                userIdHashOps.put(key, value);
            }
        }
//        清空匿名购物车
        redisTemplate.delete(CarConstatns.USERCARPRE + anneId);
        return R.success();
    }
}
